package com.zrj.handler;

import com.alibaba.fastjson.JSON;
import com.zrj.annotation.IgnoreToken;
import com.zrj.common.cache.TokenCacheManager;
import com.zrj.pojo.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author zhaorujie
 * @version 1.0
 * @date 2021/6/26 9:26
 */
public class TokenHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、从http请求头获取请求接口
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //2、检查是否有IgnoreToken注释，有则跳过认证
        if (method.isAnnotationPresent(IgnoreToken.class)) {
            IgnoreToken ignoreToken = method.getAnnotation(IgnoreToken.class);
            if (ignoreToken.required()) {
                return true;
            }
        }
        //3、从请求头获取token
        response.setContentType("application/json;charset=UTF-8");
        String token = getParam(request, "token");
        if (StringUtils.isEmpty(token)) {
            Result result = Result.error(401, "token为空");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        if (!StringUtils.isEmpty(token) && !TokenCacheManager.hasData(token)) {
            Result result = Result.error(401, "token不存在或已过期");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        return true;
    }

    /**
     * 获取参数
     * @param request
     * @param filedName
     * @return
     */
    public String getParam(HttpServletRequest request, String filedName) {
        String param = request.getParameter(filedName);
        if (StringUtils.isEmpty(param)) {
            param = request.getHeader(filedName);
        }
        return param;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
